<template>
  <div class="customs">
    <div class="breadcrumb">
      <el-breadcrumb separator=">">
        <i class="bread-ico">
          <icon name="wpexplorer"></icon>
        </i>
        <el-breadcrumb-item :to="{ path: '/' }">
          首页
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'normal-gonghai' }"
                            v-if="routeType === 'normal'">普通客户</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'social-gonghai' }"
                            v-if="routeType === 'social'">社交客户</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'normal-gonghai' }"
                            v-if="routeName === 'normal-gonghai'">公海列表</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'social-gonghai' }"
                            v-if="routeName === 'social-gonghai'">公海列表</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'normal-team-gonghai' }"
                            v-if="routeName === 'normal-team-gonghai'">团队客户</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'social-team-gonghai' }"
                            v-if="routeName === 'social-team-gonghai'">团队客户</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: '/social-customs' }"
                            v-if="routeName === 'social-customs'">社交客户列表</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/customs/'+customId }"
                            v-if="routeName === 'customsDt'">客户详情</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/customs/'+customId+'/edit' }"
                            v-if="routeName === 'editCustom'">客户编辑</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'normal-upload-customs' }"
                            v-if="routeName === 'normal-upload-customs'">名单上传列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="btn-group">
      <el-button @click="uploadDialog = true"
                 class="filter-item"
                 size="small">批量上传</el-button>
      <el-button @click="showExportFilter = !showExportFilter"
                 class="filter-item"
                 size="small">批量导出</el-button>
      <!--<el-button @click="dfUploadDialog = true" class="filter-item" size="small">导入到访</el-button>-->
    </div>
    <div class="tabpane-container"
         ref="tabpaneContainer"
         v-loading.body="loading"
         element-loading-text="拼命加载中"
         element-loading-customClass="partloading">
      <el-tabs v-model="activeName"
               @tab-click="handleClick">
        <template>
          <el-tab-pane label="公海"
                       :name="routeType + '-gonghai'"
                       :params="S(route.params)">
            <Customs :type="customType"
                     v-if="routeName === 'normal-gonghai'"
                     @changeLoading="changeLoading"
                     :tabHeight="tabHeight"></Customs>
            <SocialCustoms :type="customType"
                           v-if="routeName === 'social-gonghai'"
                           @changeLoading="changeLoading"
                           :tabHeight="tabHeight"></SocialCustoms>
          </el-tab-pane>
          <el-tab-pane label="团队"
                       :name="routeType + '-team-gonghai'"
                       :params="S(route.params)">
            <TeamCustoms v-if="routeName === (routeType + '-team-gonghai')"
                         listType="customs"
                         :teamId="team_id"
                         :isTeam="true"
                         :type="customType"
                         @changeLoading="changeLoading"
                         :tabHeight="tabHeight"></TeamCustoms>
          </el-tab-pane>
          <el-tab-pane ref="detailContainer"
                       :params="S(route.params)"
                       v-if="routeName === 'customsDt' || routeName === 'editCustom'"
                       label="客户详情"
                       name="customsDt">
            <CustomProfile v-if="routeName === 'customsDt'"
                           @changeLoading="changeLoading"
                           :tabHeight="tabHeight"></CustomProfile>
          </el-tab-pane>
          <el-tab-pane ref="editContainer"
                       :params="S(route.params)"
                       v-if="routeName === 'editCustom'"
                       label="编辑客户"
                       name="editCustom"
                       class="scroll"
                       :style="'height:' + (this.tabHeight + 80) + 'px;'">
            <EditCustom v-if="routeName === 'editCustom'"
                        @changeLoading="changeLoading"></EditCustom>
          </el-tab-pane>
          <el-tab-pane label="导出客户列表"
                       :params="S(route.params)"
                       name="export-customs">
            <ExportCustoms :type="customType"
                           v-if="routeName === 'export-customs' && !switchSite"
                           @changeLoading="changeLoading"
                           :tabHeight="tabHeight"
                           :timeStamp="exportTime"></ExportCustoms>
          </el-tab-pane>
          <el-tab-pane label="名单上传列表"
                       :name="routeType + '-upload-customs'"
                       :params="S(route.params)"
                       v-if="routeType === 'normal'">
            <UploadCustoms :type="customType"
                           v-if="routeName === 'normal-upload-customs'"
                           @changeLoading="changeLoading"
                           :tabHeight="tabHeight"></UploadCustoms>
          </el-tab-pane>
        </template>
      </el-tabs>
    </div>
    <el-dialog v-model="uploadDialog"
               top="6%">
      <template slot="title">
        <div class="uploadTitle">
          <span>上传文件</span>
        </div>
      </template>
      <el-upload v-if="uploadDialog"
                 ref="upload"
                 accept=".xls, .xlsx"
                 class="upload-wrap"
                 :action="uploadAction"
                 name="upload_file"
                 :data="uploadData"
                 :on-success="succesUpload"
                 :on-error="failedUpload"
                 :before-upload="befUpload">
        <el-button size="small"
                   type="primary">点击上传</el-button>
        <div slot="tip"
             class="el-upload__tip">
          <p>选择一个团队进行导入以及选择要上传的文件，仅支持xls格式, 文件名不能相同,下载
            <a style="color:#20a0ff;"
               :href="'http://oodoa7x5e.bkt.clouddn.com/CRM%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls?' + Math.random()">「模板」</a>
          </p>
          <div class="team"
               v-show="uploadTeamShow">
            <el-select size="small"
                       v-model="uploadTeamId">
              <el-option v-for="item in uploadTeamOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="import-results">
            <div class="import-item"
                 v-for="(obj, index, i) in responseList"
                 :key="index">
              <h4 v-if="obj.error"
                  class="error">
                <b style="font-size:14px;">{{ i + 1 }}</b> &nbsp;批量导入 「{{obj.file.name}}」 失败!
                <span v-if="obj.msg">「{{ obj.msg }}」</span>
              </h4>
              <h4 v-if="!obj.error">
                <b style="font-size:14px;">{{ i + 1 }}</b> &nbsp;上传 「 {{obj.file.name}} 」 成功, 导入结果如下: </h4>
              <el-table :show-header="showHeader"
                        v-if="obj.tableData && !obj.error"
                        :data="obj.tableData"
                        border
                        style="width: 100%">
                <el-table-column prop="desc"
                                 width="180"> </el-table-column>
                <el-table-column prop="value"> </el-table-column>
              </el-table>
              <p v-if="obj.downloadLink">导入结果下载，有啥问题都可以在这里找到喔! 亲！
                <a style="color:#20a0ff;"
                   :href="obj.downloadLink +'?'+ Math.random()">「下载」</a>
              </p>
            </div>
          </div>
        </div>
      </el-upload>
    </el-dialog>

    <el-dialog v-model="dfUploadDialog"
               top="6%">
      <template slot="title">
        <div class="uploadTitle">
          <span>上传文件</span>
          <!--<div class="team" v-show="uploadTeamShow">-->
          <!--<span>团队</span>-->

          <!--</div>-->
        </div>
      </template>
      <el-upload v-if="dfUploadDialog"
                 ref="upload"
                 accept=".xls, .xlsx"
                 class="upload-wrap"
                 :action="dfUploadAction"
                 name="upload_file"
                 :data="uploadData"
                 :on-success="succesUpload"
                 :on-error="failedUpload"
                 :before-upload="befUpload">
        <el-button size="small"
                   type="primary">点击上传</el-button>
        <div slot="tip"
             class="el-upload__tip">
          <p>选择一个团队进行导入以及选择要上传的文件，仅支持xls格式, 文件名不能相同,下载
            <a style="color:#20a0ff;"
               :href="'http://oodoa7x5e.bkt.clouddn.com/%E5%AF%BC%E5%85%A5%E5%88%B0%E8%AE%BF%E6%A8%A1%E6%9D%BF.xls?' + Math.random()">「模板」</a>
          </p>
          <div class="team"
               v-show="uploadTeamShow">
            <el-select size="small"
                       v-model="uploadTeamId">
              <el-option v-for="item in uploadTeamOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="import-results">
            <div class="import-item"
                 v-for="(obj, index, i) in responseList"
                 :key="index">
              <h4 v-if="obj.error"
                  class="error">
                <b style="font-size:14px;">{{ i + 1 }}</b> &nbsp;批量导入 「{{obj.file.name}}」 失败!
                <span v-if="obj.msg">「{{ obj.msg }}」</span>
              </h4>
              <h4 v-if="!obj.error">
                <b style="font-size:14px;">{{ i + 1 }}</b> &nbsp;上传 「 {{obj.file.name}} 」 成功, 导入结果如下: </h4>
              <el-table :show-header="showHeader"
                        v-if="obj.tableData && !obj.error"
                        :data="obj.tableData"
                        border
                        style="width: 100%">
                <el-table-column prop="desc"
                                 width="180"> </el-table-column>
                <el-table-column prop="value"> </el-table-column>
              </el-table>
              <p v-if="obj.downloadLink">导入结果下载，有啥问题都可以在这里找到喔! 亲！
                <a style="color:#20a0ff;"
                   :href="obj.downloadLink +'?'+ Math.random()">「下载」</a>
              </p>
            </div>
          </div>
        </div>
      </el-upload>
    </el-dialog>

    <SelectSite v-if="switchSite"
                @changeLoading="changeLoading"></SelectSite>
    <transition enter-active-class="bounceInRight"
                leave-active-class="bounceOutRight"
                v-on:after-leave="afterLeave">
      <CustomExportFilter v-loading.body="exportLoding"
                          class="animated"
                          v-if="showExportFilter"
                          @export="exportSubmit"
                          @cancel="exportCancel"></CustomExportFilter>
    </transition>
  </div>
</template>

<style lang="scss">
@import '../scss/index';
.echarts {
  height: 300px;
}

.customs {
  .error {
    color: red;
  }
}
.btn-group {
  overflow: hidden;

  button {
    float: left;
  }
}

.content-main {
  height: 0;
  position: relative;
  float: left;
  min-height: 100%;
  width: 85%;
  .uploadTitle {
    font-size: 1rem;
    .team {
      display: inline-block;
      margin-left: 10%;
    }
  }
}

.short {
  max-width: 300px;
}

.echart-line {
  width: 100%;
  height: 400px;
}

.bread-ico {
  float: left;
  margin-right: 8px;
  margin-top: -8px;
  width: 30px;

  .fa-icon {
    width: 100%;
    height: 100%;
  }
}

.right-content {
  .el-tabs__header {
    // margin-bottom: 0;
  }
  .el-tab-pane {
    // padding-top: 15px;
  }
  .el-tabs__content {
    // height:  30rem;
    overflow-y: auto !important;
  }
}

.badge-list .el-badge {
  margin-right: 40px;
}

.scroll {
  width: 99%;
  overflow: hidden;
  overflow-y: auto;
}

.import-item {
  border-bottom: 1px solid rgb(223, 230, 236);
}

.short.el-select {
  min-width: 300px;
}

.el-input.short-filter-input {
  width: 160px;
}

.filter-body .filter-item {
  float: left;
  .el-input__inner {
    height: 28px;
  }

  &.mgl {
    margin-left: 10px;
  }

  &.el-pagination {
    padding: 0;
  }
}
</style>

<script>
import Header from 'components/AdminHeader'
import LeftSideBar from 'components/LeftSideBar'
import SelectSite from 'components/SelectSite'
import Customs from 'components/Customs'
import EditCustom from 'components/EditCustom'
import CustomProfile from 'components/CustomProfile'
import ExportCustoms from 'components/ExportCustoms'
import CustomExportFilter from 'components/CustomExportFilter'
import UploadCustoms from 'components/UploadCustoms'

import { mapState, mapActions } from 'vuex'
import {  Popover, Breadcrumb, BreadcrumbItem,
  Tabs, TabPane, Button, Dialog, Upload, Table,
  TableColumn, Pagination, Form, FormItem, Select, Input, Option, Col} from 'element-ui'
import Config from '../config/common'
import Icon from 'vue-awesome/components/Icon.vue'
import 'vue-awesome/icons/wpexplorer'
import commonFilter from '../common/customs'
import MainPage from '../views/MainPage'

export default {
  data () {
    return {
      customClass: 'partloading',
      customData: [],
      customId: null,
      showExportFilter: false,
      loading: false,
      init: false,
      showUserPanel: false,
      docHeight: window.innerHeight + 'px',
      screenWidth: document.body.clientWidth,
      resize: false,
      activeName: 'normal-gonghai',
      uploadDialog: false,
      dfUploadDialog: false,
      uploadAction: '',
      dfUploadAction: '',
      fileList: [],
      team_id: '',
      exportLoding: false,
      filterData: {
        channel_id: null
      },
      exportTime: '',
      isInit: false,
      tabHeight: 500,
      responseList: {},
      currentPage: 1,
      customDetail: {},
      showHeader: true,
      showFileList: false,
      uploadTeamShow: false,
      uploadTeamOptions: [],
      uploadTeamId: null,
      uploadData: {
        team_id: null
      }
    }
  },

  watch: {
    routeName (routeName) {
      if (routeName !== 'home') this.activeName = routeName
      // this.updateMenuIndex('gonghai-' + this.routeType)
      this.loading = false
    },
    screenWidth (val) {
      if (!this.timer) {
        this.screenWidth = val
        this.timer = true
        const that = this

        setTimeout(function () {
          that.resize = !that.resize
          that.timer = false
        }, 400)
      }
    },
    switchSite (value) {
      if (value === false) {
        // this.loading = true
        this.initialize()
      }
    },
    uploadDialog (value) {
      console.log(value)
      if (value === false) {
        this.emptyDatas()
        this.getCustoms()
      }
      this.tableData = []
      this.fileList = []
      this.responseList = {}
      // this.$refs.upload.clearFiles()
      // }
    },
    dataDictionary (val) {

    }
  },
  methods: {
    $getTeams () {
      this.getTeams().then((response) => {
        console.log(response)
        if (response.data.errcode === 0) {
          const options = []
          response.data.results.forEach((team) => {
            options.push({
              value: team.id,
              label: team.team_name
            })
          })
          if (response.data.results.length > 1) {
            this.uploadTeamShow = true
          }
          this.uploadTeamId = response.data.results[0].id
          this.uploadTeamOptions = options
        }
      }).catch((error) => {
      })
    },
    changeLoading (loading) {
      this.init = true
      this.loading = loading
      console.log('changeLoading', loading)
    },
    afterLeave () {
      console.log('afterLeave')
      if (this.exportStatus === true) {
        if (this.routeName !== 'export-customs') {
          const params = Object.assign({ type: 'normal' }, this.$route.params)
          this.$router.push({ name: 'export-customs', params: params })
        } else {
          this.exportTime = Math.random()
        }
        this.exportStatus = false
      }
    },
    exportSubmit (status) {
      this.exportStatus = status
      this.showExportFilter = false
    },
    exportCancel (status) {
      this.exportStatus = status
      this.showExportFilter = false
    },
    handleSizeChange (val) {
      this.queryData['page_size'] = val
      this.page_size = val
      // hack
      this.setSizeInputVal(val)
      console.log(`每页 ${val} 条`)
      this.emptyDatas()
      this.getCustoms()
    },
    changeFilterData () {
      if (this.filterData.channel_id && this.filterData.channel_id.replace(' ', '')) {
        this.emptyList()
        this.getCustoms()
      } else {
        console.debug('no filter data')
        this.emptyDatas()
        this.getCustoms()
      }
    },
    emptyList () {
      this.list = []
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveCustom(this.customDetail).then((response) => {
            if (response.data.errcode === 0) {
              this.$router.push({ path: '/customs/' + this.customId })
              this.isEdit = false
              this.activeName = 'profile-detail'
              this.initCustom(this.customId)
              this.emptyDatas()
              this.getCustoms()
            }
          }).catch((err) => {
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    setSizeInputVal (val) {
      const sizeInput = this.$refs.pagination.$el.getElementsByClassName('el-input__inner')[0]
      val = val + ' ' + '条/页'
      sizeInput.value = val
    },
    handleCurrentChange (val) {
      // if (this.isInit === false && parseInt(this.$route.query.page_index)) {
      //   val = parseInt(this.$route.query.page_index)
      //   this.currentPage = val
      //   this.isInit = true
      //   return
      // }
      this.queryData['page_index'] = val
      console.log(`当前页: ${val}`)
      this.emptyDatas()
      this.getCustoms()
    },
    S (json) {
      return JSON.stringify(json)
    },
    handleClick (tab, event) {
      if (tab.name === this.routeName) return
      var params = tab.$el.getAttribute('params')
      if (params) {
        if (typeof params === 'string') {
          params = JSON.parse(params)
        }
      } else {
        params = {}
      }
      // this.loading = true
      this.init = false
      this.$router.replace({ name: tab.name, params: params })
    },
    view ($scope) {
      this.initCustom($scope.row.id)
      this.$router.push({ path: '/customs/' + $scope.row.id })
      this.customId = $scope.row.id
      this.activeName = 'profile-detail'
    },
    editCustom ($scope) {
      this.customDetail = {}
      this.$router.push({ path: '/customs/' + $scope.row.id, query: { type: 'edit' } })
      this.customId = $scope.row.id
      this.activeName = 'profile-edit'
      this.isEdit = true
      this.initCustom($scope.row.id)
    },
    emptyDatas () {
      this.list = []
      this.filterData = {}
    },
    reverse (object) {
      var NewObj = {}
      var keysArr = Object.keys(object)
      for (var i = keysArr.length - 1; i >= 0; i--) {
        NewObj[keysArr[i]] = object[keysArr[i]]
      }
      return NewObj
    },
    filterPage (value, row) {
      console.log(value, row)
      return row.page_index === value
    },
    removeEmptyValues (dataObj) {
      var freshObject = {}
      for (const key in dataObj) {
        if (dataObj[key]) freshObject[key] = dataObj[key]
      }
      return freshObject
    },
    succesUpload (response, file, fileList) {
      const results = response.results
      const all = results.success + results.failed
      const data = [
        {
          'desc': '总条数',
          'value': all + '条'
        },
        {
          'desc': '失败条数',
          'value': results.failed + '条'
        },
        {
          'desc': '成功条数',
          'value': results.success + '条'
        }
      ]
      console.log('results', results)
      this.responseList = this.reverse(Object.assign({},
        this.responseList, {
          [file.name]: {
            file: file,
            tableData: data,
            error: response.errcode !== 0,
            code: response.errcode,
            msg: response.errmsg,
            downloadLink: results.download_link
          }
        }))
    },
    failedUpload (err, file, fileList) {
      console.log(err, file, fileList)
      this.responseList = this.reverse(Object.assign({},
        this.responseList, {
          [file.name]: {
            file: file,
            error: err,
            code: 10000,
            msg: err.msg ? err.msg : '文件内容不合法',
            downloadLink: err.download_link
          }
        }))
    },
    befUpload (file) {
      if (this.uploadTeamId !== null) {
        this.uploadData.team_id = this.uploadTeamId
      } else {
        this.failedUpload({
          download_link: '',
          msg: '您必须加入一个团队！'
        }, file, [])
        return false
      }
    },
    loaded () {
      this.$nextTick(() => {
        const windowHeight = window.innerHeight
        const offsetTop = this.$refs['tabpaneContainer'].offsetTop
        this.tabHeight = windowHeight - offsetTop - 110
        this.loading = true
        console.log('loaded', loaded)
      })
    },
    initialize () {

    },
    ...commonFilter,
    ...mapActions({
      requestCustoms: 'getCustoms',
      getDictionary: 'getDictionary',
      getCustom: 'getCustom',
      saveCustom: 'saveCustom',
      updateMenuIndex: 'updateMenuIndex',
      getTeams: 'getTeams'
    })
  },
  mounted: function () {
    this.customId = this.$route.params.id
    if (this.$route.name !== 'home') {
      this.activeName = this.$route.name
      console.log('this.activeName', this.activeName)
    } else {
      this.$router.replace({ name: 'normal-gonghai', params: { type: 'normal' } })
    }

    if (!this.routeType) this.routeType = this.$routeType
    this.uploadAction = Config.CRM_API_HOST + '/users/' + this.token + '/import'
    this.dfUploadAction = Config.CRM_API_HOST + '/users/' + this.token + '/df/import'
    // this.setSizeInputVal(this.queryData.page_size)
    this.getDictionary()
    this.updateMenuIndex('gonghai-' + this.routeType)
    this.initialize()

    const teamList = Object.keys(this.user.my_team_list)
    if (teamList.length) {
      this.team_id = teamList[0]
    }

    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        this.screenWidth = window.screenWidth
      })()
    }
  },
  beforeMount () {
    this.$getTeams()
  },
  components: {
    ELHeader: Header,
    LeftSideBar: LeftSideBar,
    Customs: Customs,
    SocialCustoms: Customs,
    TeamCustoms: Customs,
    EditCustom: EditCustom,
    CustomProfile: CustomProfile,
    CustomExportFilter: CustomExportFilter,
    ExportCustoms: ExportCustoms,
    [Popover.name]: Popover,
    [Breadcrumb.name]: Breadcrumb,
    [Tabs.name]: Tabs,
    [TabPane.name]: TabPane,
    [BreadcrumbItem.name]: BreadcrumbItem,
    [Button.name]: Button,
    [Dialog.name]: Dialog,
    [Upload.name]: Upload,
    [Table.name]: Table,
    [TableColumn.name]: TableColumn,
    [Pagination.name]: Pagination,
    [Form.name]: Form,
    [Select.name]: Select,
    [Input.name]: Input,
    [Option.name]: Option,
    [FormItem.name]: FormItem,
    MainPage,
    SelectSite,
    UploadCustoms,
    'el-col': Col,
    'icon': Icon
  },
  computed: {
    ...mapState({
      user: state => state.auth.user,
      token: state => state.auth.user.token,
      dataDictionary: state => state.custom.data_dictionary,
      switchSite: state => state.custom.switch_site,
      route: state => state.route,
      path: state => state.route.path,
      routeName: state => state.route.name === 'home' ? 'normal-gonghai' : state.route.name,
      routeType: state => state.route.params && state.route.params.type ? state.route.params.type : 'normal',
      customType: state => state.route.params.type === 'social' ? 0 : 1
    })
  }
}

</script>
